App.controller("unionOrderActivityCtrl",function($scope, $rootScope, $location, $http, $compile, $stateParams, $timeout, path, publicService) {
	var alertModel = {};	//alert模态框
	$scope.search = {};
	$scope.linkParam = {		//链接参数
			user_id: null,
			source_id: null,
			activity_id:null,
			province_id:null,
			city_id:null
	};
	$scope.activity_link = "";
	var provinceCode1 = null;
	$scope.joinNumber = false;    //参与量
	$scope.createShow = true;     //创建者
	$scope.createShow2 = false;   //列表创建者
	$scope.acitvityCheckS = false;  //活动创建的显示与隐藏
	$scope.acitvityCheckS2 = false;  //活动创建的显示与隐藏
	var alertModel = {};	//alert模态框
	//提示信息
	$scope.alertMessage = function(message){
		alertModel.pannel = jqueryAlert({
			content: message,
			modal: true
		});
	}
	
	//权限
	if(userInfo.userInfoEntity){
		if(userInfo.user_level == 1){
			if(userInfo.userInfoEntity.creater == '153'){
				$scope.submitAcitvitys = true;
			}else{
				$scope.submitAcitvitys = false;
			}
		
		}else{
			$scope.submitAcitvitys = true;	
		}
	};
	var checkState = [
		                 {
			                value: "",
			      			text: "请选择",
				         },
			             {
			                value: "1",
			      			text: "未开始",
					     },
			             {
			                value: "2",
			      			text: "进行中",
					     },
					     {
			                value: "3",
				      		text: "已结束",
						     },
			                 
			          ];
	//编辑状态 
	$("#activityState").kendoDropDownList({
	    dataTextField: "text",
	    dataValueField: "value",
	    dataSource: checkState
	    });	
	
	if(userInfo.user_level == 0){
		$scope.createShow2 = false;
	}else if(userInfo.user_level == 1){
		$scope.joinNumber = true; 
	}else if(userInfo.user_level == 2){
		$scope.acitvityCheckS = true;
		$scope.acitvityCheckS2 = true;
		$scope.createShow = false;      //创建者
		$scope.createShow2 = true;
	}else if(userInfo.user_level == 3){
//		$scope.acitvityCheckS = true;
		$scope.acitvityCheckS2 = true;
		
	}
	//表格对象
	$scope.gridOptions = {
			dataSource : {
				transport : {
					read : {
						url : path+"/server/selectActivityPage",
						type : 'POST',
						dataType : "json",
						contentType : "application/json"
					},
					parameterMap : function(options, operation) {
						if (operation == "read") {
							var sort = [{dir:"desc",field:"create_time"}];
							if(options.sort!=null && options.sort.length>0 ){
								if(options.sort[0].field=="create_time"){
									options.sort[0].field="create_time";
								}else{
									options.sort[0].field="create_time";
								}
								
								sort=options.sort;
							}
							var parameter = {
								page : options.page, //当前页
								pageSize : options.pageSize,
								param:{
									activity_name:$scope.search.activity_name,//活动名称
									user_name:$scope.search.creat_name,//创建者
									state:$("#activityState").val(),//活动状态
									createTime_start:$('#startTime').val(),//创建时间(开始时间)
									createTime_end:$('#endTime').val(), //结束时间
									putaway:$("#upDownFramer").val(),//上下架
									sort:sort
										
								}
							};
							console.log('查询参数',parameter);
							return kendo.stringify(parameter);
						}
					},
				},
				pageSize : 10,
				serverPaging : true,
				serverSorting: true,
				schema : {
					data : function(d) {
						return d.result.data;
					},
					total : function(d) {
						return d.result.total; //总条数
					}
				},
			},
			pageable : {  //分页
				pageSizes: [10, 20, 50, 100],  //每页显示记录数
			  },  
			sortable: {   //排序
				//allowUnsort: false,  //允许无序
			    mode: "multiple"     //排序模式：single，multiple
			  },
			editable: false,  //true：单个编辑；popup：弹出新页面编辑
			dataBound: function () {   //序号
		        var rows = this.items();
		        var page = this.pager.page() - 1;
		        var pagesize = this.pager.pageSize();
		        $(rows).each(function () {
		            var index = $(this).index() + 1 + page * pagesize;
		            var rowLabel = $(this).find(".row-number");
		            $(rowLabel).html(index);
		        });
		    },
			columns : [
					{    
						title : "序号",
						field : "id", 
						width : "50px",
						template:"<input type='checkbox' class='recordClass' value='#: id #' />"+"<span class='row-number subTitle'></span>"
					},
					{
						field : "name",         
						title : "活动名称",     
						width : "200px"
					},
					{
						field : "user_name",         
						title : "创建者",
						hidden: $scope.createShow2,
						width : "100px"
					},
					{
						field : "create_time",         
						title : "创建日期",     
						width : "200px"
					},
					{
						field : "",         
						title : "活动周期",     
						width : "200px",
						template:function(e){
							return e.start_time + "---" + e.end_time;
						}
					},
					{
						field : "shops",         
						title : "专卖店参与量",     
						width : "100px",
						hidden: $scope.joinNumber
						
					},
					{
						field : "",         
						title : "报名人数",     
						width : "100px",
						template:function(e){
							if(e.sign_num ==null){
								return "0";
							}else{
								return e.sign_num;
							}
						}
					},
					{
						field : "putaway",         
						title : "上下架",     
						width : "100px",
						values: [
						         { text: "下架", value: 0 },
						         { text: "上架", value: 1 }
				        ],
					},
					{
						field : "state",         
						title : "状态",     
						width : "100px",
						values:checkState
					},
					{
						field : "",         
						title : "操作",     
						width : "150px",
						template: function(e){
					    	if(userInfo.user_level==0){  //开发者
					    		var	template_html = "";
					    		
					    		template_html += '<div class="operation k-state-default width_2" ng-click="lookDetails(\''+e.id+'\')">查看</div>';
					    		template_html += '<div class="operation k-state-default width_2" ng-click="activeDetails(\''+e.id+'\')">活动详情</div>';
					    		
					    		return template_html;
					    	}else if(userInfo.user_level==3){  //三级商户 
					    		var	template_html = "";
					    		if(e.state==1 || e.state==2){	//未开始，进行中+id+',\''+OneObj_2.name+'\'
					    			template_html += '<div class="operation k-state-default width_4" ng-click="copyLink('+e.user_id+',\''+e.id+'\')">复制链接</div>';
					    			template_html += '<div class="operation k-state-default width_4" ng-click="lookDetails(\''+e.id+'\')">查看</div>';
					    			template_html += '<div class="operation k-state-default width_4" ng-click="activeDetails(\''+e.id+'\')">活动详情</div>';
					    			if(e.putaway==0){	//下架
					    				template_html += '<div class="operation k-state-default width_4" ng-click="putawayFrame('+e.id+',1)">上架</div>';
					    			}else if(e.putaway==1){	//上架
					    				template_html += '<div class="operation k-state-default width_4" ng-click="putawayFrame('+e.id+',0)">下架</div>';
					    			}
					    		}else if(e.state==3){	//已结束
					    			template_html += '<div class="operation k-state-default width_4" ng-click="lookDetails(\''+e.id+'\')">查看</div>';
					    			template_html += '<div class="operation k-state-default width_4" ng-click="activeDetails(\''+e.id+'\')">活动详情</div>';
					    		}
					    		
					    		return template_html;
					    	}else if(userInfo.user_level==2){  //二级商户
					    		var	template_html = "";
					    		
					    		if(e.state==1 || e.state==2){	//未开始，进行中
					    			template_html += '<div class="operation k-state-default width_3" ng-click="editDetails(\''+e.id+'\')">编辑</div>';
					    			template_html += '<div class="operation k-state-default width_3" ng-click="activeDetails(\''+e.id+'\')">活动详情</div>';
					    			if(e.putaway==0){	//下架
					    				template_html += '<div class="operation k-state-default width_3" ng-click="putawayFrame('+e.id+',1)">上架</div>';
					    			}else if(e.putaway==1){	//上架
					    				template_html += '<div class="operation k-state-default width_3" ng-click="putawayFrame('+e.id+',0)">下架</div>';
					    			}
					    		}else if(e.state==3){	//已结束
					    			template_html += '<div class="operation k-state-default width_3" ng-click="editDetails(\''+e.id+'\')">编辑</div>';
					    			template_html += '<div class="operation k-state-default width_3" ng-click="activeDetails(\''+e.id+'\')">活动详情</div>';
					    		}
					    		
					    		return template_html;	
					    	}else if(userInfo.user_level==1){  //一级商户
					    		var	template_html = "";
					    		
					    		template_html += '<div class="operation k-state-default width_4" ng-click="lookDetails(\''+e.id+'\')">查看</div>';
				    			template_html += '<div class="operation k-state-default width_2" ng-click="activeDetails(\''+e.id+'\')">活动详情</div>';
					    		
					    		return template_html;				    		
					    	}
					    },
					}
			]
	};
	
	//查询
	$scope.search = function(){
		$scope.grid.dataSource.page(1);
	}
	
	//全选，取消
	$scope.chooseAll = function(className,flag){
		publicService.chooseAllByClassName(className,flag);
	}
	//查看
	$scope.lookDetails = function(id){
		var params = {method:"look",brandId:id,backUrl:"unionOrderActivity"};
		$location.path("/addUnionOrderActivity/"+angular.toJson(params));
	}	
	//编辑
	$scope.editDetails = function(id){
		var params = {method:"editpulish",brandId:id,backUrl:"unionOrderActivity"};
		$location.path("/addUnionOrderActivity/"+angular.toJson(params));
	}	

	//查看详情
	$scope.activeDetails = function(id){
		var params = {brandId:id};
		$location.path("/activityLook/"+angular.toJson(params));
		console.log(id);
	}
	//上架
	$scope.putawayFrame = function(id,num){
		$http({
			   url: path+"/server/updateActivityPutaway",
			   method: 'POST',
			   data:{
					   id:id,
					   putaway:num
			   } 
		}).success(function(data){
			if(data.code == "0"){
				alert("操作成功！");
				$scope.search();
			}
		}).error(function(data){
			console.log(data);   
		})
	}
	//活动审核
	$scope.activitySet = function(){
		$location.path("/activitySet");
	}
	//新增活动
	$scope.createActivity = function(){
		var params = {method:"add",backUrl:"unionOrderActivity"};
		$location.path("/addUnionOrderActivity/"+angular.toJson(params));
	}
	//复制链接(弹框)
	$scope.copyLink = function(user_id,activity_id){
		
		$scope.linkParam.user_id = user_id;
		$scope.linkParam.activity_id = activity_id;
		$scope.linkParam.province_id = null;
		$scope.linkParam.city_id = null;
		$("#customerSource").data("kendoDropDownList").value('')
		$("#province1").data("kendoComboBox").value('')
		var city = {};
		city.code = '';
		city.name = '请选择';
		var citys =[];
		citys.push(city)
		$("#city1").data("kendoComboBox").setDataSource(citys);
		$("#city1").data("kendoComboBox").value('')
		$scope.tipWindow.center().open();   //打开弹框 
		$scope.activity_link = path+"/registration.html?"+$scope.linkParam.user_id+"-"+$scope.linkParam.source_id+"-"+$scope.linkParam.activity_id+
		"-"+$scope.linkParam.province_id+"-"+$scope.linkParam.city_id
		;
		//var links1= path+"/registration.html?"+id+"-1";
		
	};
	

	//点击复制
	$scope.clickLink = function(){
		   var clipboard3 =null;
	$('#clikButtons').removeAttr('data-clipboard-target');
		if($scope.linkParam.province_id && $scope.linkParam.province_id !=""){
			if(!$scope.linkParam.city_id || $scope.linkParam.city_id ==""){
			//	$scope.alertMessage("请选择市");
				alert('请选择城市！');
				clipboard3 =null;
				return;
			}else{
				$('#clikButtons').attr('data-clipboard-target','#linkContent')
				  clipboard3 = new Clipboard('#clikButtons');   
				   
				   clipboard3.on('success', function(e) {  
					  /* if(alertModel.copy_yes){
						   alertModel.copy_yes.show();
						  
					   }else{
						   alertModel.copy_yes = jqueryAlert({
								content: "复制成功！",
								modal: true
							});
					   }*/
						alert('复制成功！');
						$('#clikButtons').removeAttr('data-clipboard-target');
					  // $scope.alertMessage("复制成功！")
						    clipboard3 =null;
				   });  
				   clipboard3.on('error', function(e) {  
					  /* if(alertModel.copy_no){
						   alertModel.copy_no.show();
					   }else{
						   alertModel.copy_no = jqueryAlert({
								content: "值失败！请手动复制！",
								modal: true
							});
					   }*/
					   alert('复制失败！请手动复制！');
					  //$scope.alertMessage("复制失败！请手动复制！！")
				   }); 
			}
		}else{
			$('#clikButtons').attr('data-clipboard-target','#linkContent')
			  clipboard3 = new Clipboard('#clikButtons');   
			   
			   clipboard3.on('success', function(e) {  
				  /* if(alertModel.copy_yes){
					   alertModel.copy_yes.show();
					  
				   }else{
					   alertModel.copy_yes = jqueryAlert({
							content: "复制成功！",
							modal: true
						});
				   }*/
				   $scope.alertMessage("复制成功！")
				   $('#clikButtons').removeAttr('data-clipboard-target');
				    clipboard3 =null;
			   });  
			   clipboard3.on('error', function(e) {  
				  /* if(alertModel.copy_no){
					   alertModel.copy_no.show();
				   }else{
					   alertModel.copy_no = jqueryAlert({
							content: "值失败！请手动复制！",
							modal: true
						});
				   }*/
				   $scope.alertMessage("复制失败！请手动复制！！")
			   }); 
		}
	
		  
	}
	
	//封装链接地址
	$scope.packLinkUrl = function(source_id,province_id,city_id){
		$scope.linkParam.source_id = source_id;
		
		if( !province_id && !city_id ){
			
		}else{
			if(province_id){
				$scope.linkParam.province_id = province_id;
			}else{
				$scope.linkParam.province_id = null;
			}
			if(city_id){
				$scope.linkParam.city_id = city_id;
			}else{
				$scope.linkParam.city_id = null;
			}
		}
		
		
		
		
		
		var linkUrl = path+"/registration.html?"+$scope.linkParam.user_id+"-"+$scope.linkParam.source_id+"-"+$scope.linkParam.activity_id+
		"-"+$scope.linkParam.province_id+"-"+$scope.linkParam.city_id;
		$scope.activity_link = linkUrl;
		$scope.$digest();
	};
	
	
	publicService.initDate("startTime");	//开始时间
	publicService.initDate("endTime");		//结束时间
	publicService.initActivityShowHidden("upDownFramer");		//初始化【上下架】
	publicService.initCustomerSource("customerSource",$scope.packLinkUrl);		//初始化【消费者来源】
	
	//初始化省
	$scope.initProvince = function(){
		$("#province1").kendoComboBox({
		    dataTextField: "name",
		    dataValueField: "code",
		    placeholder: "省",
		    filter: "contains",
		    dataSource: {
		      serverFiltering: true,
	          transport: {
	              read: {
	            	  type : 'GET',
	                  url: path+"/server/province",
	                  dataType : "json"
	              }
	          },
	          schema : {
					data : function(d) {
						var result = d.result;
						var obj ={};
						obj.name ="请选择";
						obj.code ="";
						result.unshift(obj)
						return result;
					}
				},
	      },
	      change: function(e) {
	    	    var valueList = this.value();
	    	    $scope.linkParam.province_id = valueList;
	    	    $scope.linkParam.city_id = null
	    	    provinceCode1 = valueList;
	    	    $scope.packLinkUrl($scope.linkParam.source_id,provinceCode1);
	    	    if(valueList == ""){
	    	    	var obj ={};
					obj.name ="请选择";
					obj.code ="";
					var citys = [];
					citys.push(obj);
	    	    	$scope.initCity(citys);
	    	    }else{
	    	    	$scope.getCityData(valueList);
	    	    }
	    	    
	    	    
	      }
		});
	}
	
	//获取市数据
	$scope.getCityData = function(provinceCode,defaultVal){
		$http({
			   url: path+"/server/city/"+provinceCode,
			   method: 'GET'
		}).success(function(data){
			var result = data.result;
			var obj ={};
			obj.name ="请选择";
			obj.code ="";
			result.unshift(obj)
			$scope.initCity(result,defaultVal);
		}).error(function(data){
			console.log(data);   
		})
	};
	
	//初始化市
	$scope.initCity = function(cityData,defaultVal){
		if(cityData){
			var plugObj = $("#city1").data("kendoComboBox");
			plugObj.value("");
			plugObj.setDataSource(cityData);
			if(defaultVal){
				plugObj.value(defaultVal);
			}
		}else{
			$("#city1").kendoComboBox({
			    dataTextField: "name",
			    dataValueField: "code",
			    placeholder: "市",
			    filter: "contains",
			    dataSource: [],
			    change: function(e) {
			    	 var valueList = this.value();	
			    	 $scope.linkParam.city_id = valueList;
			    	$scope.packLinkUrl($scope.linkParam.source_id,provinceCode1,valueList)
		      }
			});
		}
	}
	
	$scope.initProvince();			//初始化省（参与商户）
	$scope.initCity();				//初始化市（参与商户）
});